import { createRouter, createWebHashHistory } from "vue-router";
import { createRouterLayout } from "vue-router-layout";
const modules = import.meta.glob("../pages/**/*.vue");
const RouterLayout = createRouterLayout((layout) => {
	return import(`../layouts/${layout}-layout.vue`);
});

let routeMap = {
	"/": {
		name: "main",
		path: "/",
		component: RouterLayout,
		children: [],
	},
};
let routes = [routeMap["/"]];

for (let path in modules) {
	let route = { component: modules[path] };
	let loginRegex = /^\/login(?=\/)/;
	let mainRegex = /^\/main(?=\/)/;
	let _path = path.replace(/^\.\.\/pages/, "").replace(/\.vue$/, "");
	if (loginRegex.test(_path)) {
		_path = _path.replace(loginRegex, "");
		route.name = _path.replace(/^\//,"");
		route.path = _path;
		routes.push(route);
	} else if (mainRegex.test(_path)) {
		_path = _path.replace(mainRegex, "");
		route.name = _path.replace(/^\//,"");
		route.path = _path;
		if (routeMap["/"].children.length === 0) {
			routeMap["/"].redirect = route.path;
		}
		routeMap["/"].children.push(route);
	}
}

const router = createRouter({
	history: createWebHashHistory(),
	routes: routes,
});

router.beforeEach((to, _from, next) => {
	console.log(to)
	// window.document.title = to.meta.title;
	next();
});

export default router;
